import { CzmESObjectWithLocation } from "../../base";
import { ESCesiumViewer } from "../../../ESCesiumViewer";
import * as Cesium from 'cesium';
import { ESBoxEntity } from "earthsdk2s";

export class CzmESBoxEntity extends CzmESObjectWithLocation<ESBoxEntity> {
    static readonly type = this.register(ESBoxEntity.type, this);
    private _boxEnt: Cesium.Entity | undefined;
    constructor(sceneObject: ESBoxEntity, czmViewer: ESCesiumViewer) {
        super(sceneObject, czmViewer);
        const viewer = czmViewer.viewer;
        if (!viewer) {
            console.warn(`viewer is undefined!`);
            return;
        }
        const entities = viewer.entities;
        console.log('CzmESBoxEntity', this);

        const position = () => {
            return Cesium.Cartesian3.fromDegrees(...sceneObject.position);
        }


        {//创建
            const createEntity = (position: Cesium.Cartesian3) => {
                const ent = entities.add({
                    show: sceneObject.show,
                    position,
                    box: {
                        dimensions: new Cesium.Cartesian3(...sceneObject.size),
                    },
                });
                return ent;
            }
            const pos = position();
            this._boxEnt = createEntity(pos);
        }

        //对象销毁时移除对象
        this.d(() => {
            this._boxEnt && entities.remove(this._boxEnt);
            this._boxEnt = undefined;
        });



        {//position
            const updatePosition = () => {
                //@ts-ignore
                this._boxEnt && (this._boxEnt.position = position());
            }
            this.d(sceneObject.positionChanged.don(updatePosition));
        }


        {//show控制
            const updateShow = () => { this._boxEnt && (this._boxEnt.show = sceneObject.show); };
            this.d(sceneObject.showChanged.don(updateShow));
        }

        {//属性变化
            const update = () => {
                //@ts-ignore
                this._boxEnt && this._boxEnt.box && (this._boxEnt.box.dimensions = new Cesium.Cartesian3(...sceneObject.size));
            };
            this.d(sceneObject.sizeChanged.don(update));

        }

        { //flyTo
            this.d(sceneObject.flyToEvent.don(() => {
                this._boxEnt && viewer.flyTo(this._boxEnt);
            }));
        }
    }

}
